﻿using UnityEngine;

public class PlayerCounterState:PlayerStateBase
{
    public PlayerCounterState(ControllerBase controller, StateMachineBase stateMachine, string stateName, string animatorParameter) 
        : base(controller, stateMachine, stateName, animatorParameter)
    {
    }

    private bool  hasCountered;
    public override void Enter()
    {
        base.Enter();
        SelfController.mAnimator.SetBool(Setting.AnimatorSuccessfulCounter,false);
        SelfController.SetVelocity(Vector2.zero);
        hasCountered = false;
    }

    public override void Exit()
    {
        base.Exit();
        SelfController.mAnimator.SetBool(Setting.AnimatorSuccessfulCounter,false);
    }

    public override void Update()
    {
        base.Update();
        SelfController.SetVelocity(Vector2.zero);
        if (!hasCountered)
        {
            Collider2D[] collider2Ds = Physics2D.OverlapCircleAll(SelfController.GetAttackCheckPos(),
                Setting.attackRadius);
            
            foreach (Collider2D item in collider2Ds)
            {
                EnemyStateController enemyStateController = item.GetComponent<EnemyStateController>();
                if (enemyStateController != null)
                {
                    //是否可以反击
                    if (enemyStateController.canBeCounter)
                    {
                        stateDuration = -5;
                        hasCountered = true;
                        //进入反击成功
                        SelfController.mAnimator.SetBool(Setting.AnimatorSuccessfulCounter,true);
                        //触发被反击
                        enemyStateController.TriggerStunned();
                        //创造残影攻击
                        var pos = SelfController.transform.position+Vector3.right * (SelfController.faceDir * 3);
                        SkillManager.Instance.CreateCloneAttackWithCoroutine
                            (pos, SelfController.faceDir,Setting.curCounterSkill,false,0.5f);
                        
                        return;
                    }
                }
            }
            
        }

        if (stateDuration>Setting.counterDuration||triggerFinish)
        {
            stateMachine.ChangeState(Setting.idle);
            return;
        }
    }
}